package com.ytd.smartcanteen.weighting.util;

import android.text.TextUtils;

import com.ytd.common.bean.BaseRequest;
import com.ytd.common.net.NetCallBack;
import com.ytd.common.net.RequestManager;
import com.ytd.common.util.LogUtil;
import com.ytd.common.util.ThreadUtil;
import com.ytd.smartcanteen.weighting.bean.MealInfo;
import com.ytd.smartcanteen.weighting.bean.MealTimeInfo;
import com.ytd.smartcanteen.weighting.bean.OrderBean;
import com.ytd.smartcanteen.weighting.bean.request.UploadFoodWeightRequestData;
import com.ytd.smartcanteen.weighting.bean.response.UploadFoodWeightResponse;
import com.ytd.smartcanteen.weighting.constants.Constants;
import com.ytd.smartcanteen.weighting.dao.WeightingDB;
import com.ytd.smartcanteen.weighting.devices.LEDManager;
import com.ytd.smartcanteen.weighting.devices.ScaleManager;
import com.ytd.smartcanteen.weighting.fragment.ConsumeFragment;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消费页网络工具
 *
 * @author gaoguanchao
 * @since 2023/12/7 0007
 */
public class ConsumeNetUtil {
    private final static Map<OrderBean, Integer> timeOutOrderBeans = new HashMap<>();

    public static void settlement(MealInfo mealInfo, OrderBean data, boolean isLocal, boolean timeout) {
        data.foodId = mealInfo.foodId;
        MealTimeInfo mealTimeInfo = FoodManager.getInstance().getMealTime(mealInfo.mealTimeId);
        data.setFood(mealInfo);
        if (mealTimeInfo != null) {
            data.mealTimeName = mealTimeInfo.mealTimeName;
            if (TextUtils.isEmpty(data.mealTimeTypeCode)) {
                data.mealTimeTypeCode = mealTimeInfo.mealTimeTypeCode;
            }
            if (TextUtils.isEmpty(data.mealStartTime)) {
                data.mealStartTime = mealTimeInfo.mealStartTime;
            }
            if (TextUtils.isEmpty(data.mealEndTime)) {
                data.mealEndTime = mealTimeInfo.mealEndTime;
            }
        }
        data.createSign();
        if (isLocal && !timeout) {
            saveLocal(data);
            return;
        }
        requestAddOrder(data, timeout);
        if (timeout) {
            ThreadUtil.executeMainDelayed(ConsumeNetUtil::handlerTimeoutOrder, 30 * 1000L);
        }
    }


    private static void requestAddOrder(OrderBean data, boolean isTimeout) {
        BaseRequest request = new BaseRequest();
        request.interfaceName = Constants.ADD_ORDER_SNAPSHOT;
        request.data = data;
        request.timeout = 5000;
        RequestManager.getInstance().request(request, new NetCallBack<Object>() {
            @Override
            public void onSuccess(Object result) {
                LogUtil.d("add order onSuccess " + data.orderId + "--foodWeight:" + data.foodWeight);
                uploadFoodWeight();
                if (isTimeout) {
                    delLocal(data);
                    timeOutOrderBeans.remove(data);
                }
            }

            @Override
            public void onFail(int code, String msg) {
                if (code == RequestManager.TIME_OUT_CODE || isTimeout) {
                    Integer integer = timeOutOrderBeans.get(data);
                    if (integer == null) {
                        timeOutOrderBeans.put(data, 0);
                    } else {
                        timeOutOrderBeans.put(data, ++integer);
                    }
                }
                saveLocal(data);
            }
        });
    }

    private static void handlerTimeoutOrder() {
        if (timeOutOrderBeans.isEmpty()) {
            return;
        }
        List<OrderBean> orderBeans = new ArrayList<>();
        for (Map.Entry<OrderBean, Integer> orderBeanIntegerEntry : timeOutOrderBeans.entrySet()) {
            OrderBean key = orderBeanIntegerEntry.getKey();
            Integer value = orderBeanIntegerEntry.getValue();
            if (value > 3) {
                orderBeans.add(key);
                continue;
            }
            requestAddOrder(key, true);
        }
        for (OrderBean orderBean : orderBeans) {
            timeOutOrderBeans.remove(orderBean);
        }
        ThreadUtil.executeMainDelayed(ConsumeNetUtil::handlerTimeoutOrder, 30 * 1000L);
    }


    public static void uploadFoodWeight() {
        UploadFoodWeightRequestData data = new UploadFoodWeightRequestData();
        BigDecimal stableWeight = ScaleManager.getInstance().getStableWeight();
        int weight = stableWeight.multiply(ConsumeFragment.multiplyValue).intValue();
        data.foodWeight = String.valueOf(weight);
        BaseRequest request = new BaseRequest();
        request.interfaceName = Constants.UPLOAD_FOOD_WEIGHT;
        request.data = data;
        RequestManager.getInstance().request(request, new NetCallBack<UploadFoodWeightResponse>() {
                    @Override
                    public void onSuccess(UploadFoodWeightResponse result) {
                        if (result.lackOfFood && result.showWarning) {
                            //开启缺菜闪烁
                            LEDManager.getInstance().flickerYellow();
                        } else {
                            LEDManager.getInstance().setCloseFlicker(true);
                        }
                    }

                    @Override
                    public void onFail(int code, String msg) {

                    }
                }
        );
    }

    private static void saveLocal(OrderBean data) {
        WeightingDB.getInstance().getOrderBeanDao().insert(data);
        LogUtil.d("add order saveLocal " + data);
    }

    private static void delLocal(OrderBean data) {
        WeightingDB.getInstance().getOrderBeanDao().delete(data);
        LogUtil.d("order delLocal " + data);
    }
}
